package com.hengjun.baccarat.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.hengjun.baccarat.R;
import com.hengjun.baccarat.common.ConfigData;
import com.hengjun.baccarat.utils.ThreadManager;

public class UpdateManager {
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;
	private String updateReadMe = null;
	private String baccarat = null;
	boolean isUpdate = false;
	private String versionName;
	private String serviceCode = null;
	private String readMe;
	private Context mContext;
	/* 更新进度条 */
	private ProgressBar mProgress;
	private TextView schedule;
	private Dialog mDownloadDialog = null;
	private String xml = "";
	private UpdateSoft updateSoft ;
	public Dialog updateDialog = null;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case 1:
				// 设置进度条位置
				mProgress.setProgress(progress);
				schedule.setText("下載進度:" + String.valueOf(progress) + "%");
				break;
			case 2:
				// 安装文件
				installApk();
				break;
			case 3:
				Toast.makeText(mContext, R.string.soft_update_noIn,
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		updateDialog = null;
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate() {
		updateSoft = new UpdateSoft();
		updateSoft.start();
	}

	public void closeUpdate() {
		if (updateDialog != null) {
			updateDialog.dismiss();
		}
		if(mDownloadDialog != null){
			mDownloadDialog.dismiss();
		}
	}

	/**
	 * 检查软件是否有更新版本
	 */
	private class UpdateSoft extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				String a = UrlConn.getUpdateSoftURL();
				xml = UrlConn.getUpdateSoftXML(a);
				XmlPullParser parser = Xml.newPullParser();
				parser.setInput(new StringReader(xml));
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if ("config".equals(parser.getName())) {
							int count = parser.getAttributeCount();
							for (int i = 0; i < count; i++) {
								String key = parser.getAttributeName(i);
								if ("totalByte".equals(key)) {
									parser.getAttributeValue(i);
								} else if ("url".endsWith(key)) {
									parser.getAttributeValue(i);
								} else if ("ver".endsWith(key)) {
									serviceCode = parser.getAttributeValue(i);
								}
							}
						} else if (parser.getName().equalsIgnoreCase("update")) {
							if (baccarat == null) {
								baccarat = parser.nextText();
								ConfigData.baccarat = baccarat;
							} else {
								updateReadMe = parser.nextText();
							}
						}
						break;
					case XmlPullParser.END_TAG:
						break;
					}
					eventType = parser.next();
				}

				versionName = getVersionName();
				if (!xml.equals("")) {
					if (!serviceCode.equals(versionName)) {
						ConfigData.readMe = UrlConn
								.getUpdateReadME(updateReadMe);
						ThreadManager.handler.obtainMessage(1001)
								.sendToTarget();
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 获取软件版本号
	 */
	private String getVersionName() {
		String versionName = null;
		try {
			PackageManager pm = mContext.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);
			versionName = pi.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 显示软件更新对话框
	 */

	public void showNoticeDialog() {
		readMe = ConfigData.readMe;
		baccarat = ConfigData.baccarat;
		// 构造对话框
		updateDialog = new Dialog(mContext, R.style.MyDialogStyle);
		updateDialog.setContentView(R.layout.dialog_layout);
		TextView messageView = (TextView) updateDialog
				.findViewById(R.id.show_update);
		Button detemind = (Button) updateDialog.findViewById(R.id.btn_ok);
		Button cancel = (Button) updateDialog.findViewById(R.id.btn_cancel);
		Spanned str = Html.fromHtml(readMe);
		String message = str.toString().substring(4,
				str.toString().length());
		messageView.setText(message);
		detemind.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				updateDialog.dismiss();
				showDownloadDialog();
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				updateDialog.dismiss();
			}
		});
		updateDialog.show();
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		// 构造软件下载对话框
		mDownloadDialog = new Dialog(mContext, R.style.MyDialogStyle);
		mDownloadDialog.setContentView(R.layout.download_dialog);
		mProgress = (ProgressBar) mDownloadDialog.findViewById(R.id.progressBar1);
		Button exit = (Button) mDownloadDialog.findViewById(R.id.button1);
		schedule = (TextView) mDownloadDialog.findViewById(R.id.textView2);
		exit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDownloadDialog.dismiss();
				cancelUpdate = true;
			}
		});
		mDownloadDialog.show();
		// 下載文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 下载文件线程
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory()
							+ "/";
					mSavePath = sdpath + "Baccarat";

					URL url = new URL(UrlConn.UpdateSoft2
							+ "/androidBacarat/update/" + baccarat);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, "Baccarat.apk");
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 101);
						// 更新进度
						mHandler.sendEmptyMessage(1);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(2);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, "Baccarat.apk");
		if (apkfile.exists()) {
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(apkfile),
					"application/vnd.android.package-archive");
			mContext.startActivity(intent);
		} else {
			mHandler.sendEmptyMessage(3);
		}
	}
}
